package engine.newUi
{
	import engine.data.BindManage;
	import engine.data.ModelLocator;
	import engine.data.ObjectData;
	import engine.data.View;
	import engine.data.ViewObject;
	import engine.event.SoundEvent;
	import engine.flag.GameDefine;
	import engine.flag.ResourcesPath;
	import engine.logic.DoubleClickManager;
	import engine.logic.LogSendLogic;
	import engine.logic.McPool;
	import engine.logic.MenuListManager;
	import engine.logic.event.LogicEvent;
	import engine.net.event.CustomMsgEvent;
	import engine.net.messages.CustomToClientFlag;
	import engine.net.messages.CustomToServerFlag;
	import engine.net.mgr.SystemSender;
	import engine.scene.SceneManager;
	import engine.tip.TipsMainLogic;
	import engine.ui.AlertUI;
	import engine.ui.MainLogic;
	
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.MouseEvent;
	
	import newx.com.config.StaticIni;
	import newx.com.control.NxClip;
	import newx.com.control.button.NxButton;
	import newx.com.control.tab.NxTabEvent;
	import newx.com.control.text.NxLabel;
	import newx.com.control.window.NxWindowEvent;

	/**
	 *背包逻辑 
	 * @author yanghr
	 * 
	 */	
	public class PackLogic
	{
		private static var _self:PackLogic;
		private var bindFlag:int	=	-1;
		private var bindView:int	=	-1;
		private var _model:ModelLocator;
		private var _blind:BindManage;
		private var _tips:TipsMainLogic;
		private var _gridData:Array	=	[];
		private var _propData:Array	=	[];
		private var _lockIndex:int	=	0;
		private var _unlock:int
		
		private var _ui:PackUI;
		private var _roll_cell:MovieClip;
		private var _tipIndex:int;
		/**
		 *单页最大数 
		 */		
		private var _one_page_max:int;
		/**
		 *当前页数 
		 */		
		private var _currentPage:int=1;
		
		private const NORMAL:int	=	1;
		private const ROLL:int		=	2;
		private const DISABLE:int	=	3;
		private const DISABLE_SELECTED:int=4;
		//存放遮罩的数组
		private var _veilArr:Array=[];
		private var _doubleClickManager	: 	DoubleClickManager;
		
		public static function getInstance():PackLogic
		{
			if(_self==null)
			{
				_self	=	new PackLogic();
			}
			return _self
		}
		
		public function Init():void
		{
			_model	=	ModelLocator.getInstance();			
			_blind	=	BindManage.getInstance();
			_tips	=	TipsMainLogic.instance;
			ui.shopBtn.label=StaticIni.getSwfLangStr("UIString_1000200");
			ui.clearUpBtn.label=StaticIni.getSwfLangStr("UIString_1000292");
			ui.storageBtn.label=StaticIni.getSwfLangStr("UIString_1000202");
			_doubleClickManager	= DoubleClickManager.getInstance();
			
			_doubleClickManager.addDoubleClick( PackLogic, singleClick, doubleClick );
			
			initAllCell();
			_ui.page.dataProvider=[{label:"1",data:1},{label:"2",data:2}]
			_veilArr =["custSkin_45","custSkin_46","custSkin_47","custSkin_48","custSkin_49"];
			_model.addEventListener(String(CustomToClientFlag.CLIENT_CUSTOMMSG_SELL_ITEM),saleAction);
		}
		private function saleAction(e:CustomMsgEvent):void
		{
			var index:int= e.pList[0];
			if(index == 1)
			{
				SellUI.getInstance().dispatchEvent(new Event("clicksale"));
			}
		}
		private function initAllCell():void
		{
			var len:int	=	ui.group.row*ui.group.col
			for (var i:int 	=	 0; i < len; i++) 
			{
				var cell:MovieClip	=	ui.group.getItemByIndex(i);
				//图片
				cell.bg	=	new NxClip();
				cell.bg.isCache = true;
				//字符
				cell.lable	=	new NxLabel();
				cell.lable.x=32//cell.width-25;
				cell.lable.y=25//cell.height-20;
				cell.lable.color=0xffffff;
				cell.lable.glowColor = 0x081f22;
				//上锁
				
				cell["img2"].addChild(cell.bg);
				cell.index		=		i;
				cell.addChild(cell.lable);
				cell.gotoAndStop(DISABLE);
				_gridData.push(cell);	

			}
			_one_page_max=_gridData.length;
		}
		/**
		 * 添加事件
		 */		
		public function addAllListener():void
		{
			ui.windowBG	.addEventListener(	NxWindowEvent.WINDOW_CLOSE,	onClickClose);	
			ui.windowBG.addEventListener(MouseEvent.CLICK,btnClickhandle);
			_ui.page.addEventListener(NxTabEvent.TAB_CLICK,tabClickHandle);
			ui.group.addEventListener(MouseEvent.ROLL_OVER, rollOver,true);
			ui.group.addEventListener(MouseEvent.ROLL_OUT,rollOut,true);
			ui.group.addEventListener(MouseEvent.CLICK,onClickItem);
		}
		private function tabClickHandle(e:NxTabEvent):void
		{
			_currentPage=e.item.data;
			refreshCurrentPage();
		}
		private function refreshCurrentPage():void
		{
			unlock=_unlock
			for (var i:int =0; i <_one_page_max; i++) 
			{
				refreshIndex(i+(_one_page_max*(_currentPage-1)));
			}
		}
		/**
		 * 删除事件 
		 */		
		public function removeAllListener():void
		{
			ui.windowBG	.removeEventListener(	NxWindowEvent.WINDOW_CLOSE,	onClickClose);
			ui.windowBG.removeEventListener(MouseEvent.CLICK,btnClickhandle);
			_ui.page.removeEventListener(NxTabEvent.TAB_CLICK,tabClickHandle);
			ui.group.removeEventListener(MouseEvent.ROLL_OVER, rollOver,true)
			ui.group.removeEventListener(MouseEvent.ROLL_OUT,rollOut,true)
			ui.group.removeEventListener(MouseEvent.CLICK,onClickItem);
			_blind.UnbindView(View.VIEWPORT_TOOL,bindFlag);
			_blind.UnbindProp(_model.scene.GetView(View.VIEWPORT_TOOL),"BaseCap",bindView);
		}
		
		private function doubleClick( evt : MouseEvent ):void
		{
			if(TreasureShopUI.getInstance().created) return;
			var cell:MovieClip	=	evt.target as MovieClip;
			
			if(_gridData.indexOf(cell)	<	0)
			{
				cell	=	(evt.target as DisplayObject).parent.parent as MovieClip;
			}
			
			if(cell==null||cell.dataobj == null||cell.dataobj[_currentPage]==null)
				return ;
			//双击出售
			if(SellUI.getInstance().created == true)
			{
				sellEquip(cell.dataobj[_currentPage]);
			}
			else if(DepotUI.getInstance().created)
			{
				SystemSender.getInstance().CustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_MOVEITEM,
					View.VIEWPORT_TOOL, int( cell.dataobj[_currentPage].ObjKey ),
					View.VIEWPORT_STORE, 0 );
			}
			else 
			{
				var itemType : int = cell.dataobj[_currentPage].GetPropertiesEx("ItemType") 
				if( itemType == GameDefine.ItemType_COMPOSE )
				{
					ComposeItemLogic.getInstance().SetItem((cell.dataobj[_currentPage] as ViewObject),1,View.VIEWPORT_TOOL,0);
					return;
				}else if( itemType == GameDefine.ItemType_EUIP )
				{
					equip(cell.dataobj[_currentPage]);
					if( !MyPropertyLogic.getInstance().ui.created )
					{
						MyPropertyLogic.getInstance().ui.showOrHide();
					}

					_model.dispatchEvent(new SoundEvent(SoundEvent.EQUIP_UP));
				}else if( itemType == GameDefine.ItemType_GOLDBOX )
				{
					SystemSender.getInstance().CustomMsg( CustomToServerFlag.CLIENT_CUSTOMMSG_USEITEM,View.VIEWPORT_TOOL, int( cell.dataobj[_currentPage].ObjKey ) );
				}
			}
		}
		/**
		 *掉这个函数的时候不要打开界面！！！！！！！！！！！！！！！！！！ 
		 * @param itemObj
		 * @viewID 指定要装备的视图id   默认就自动选择人物伙伴上的视图
		 * 
		 */		
		public function equip( itemObj : ViewObject ,viewID:int=-1):void
		{
			if(!itemObj)return ;
			var	equitType 	: 	String	=	itemObj.GetProperties("EquipType");
			if(viewID!=-1)
			{
				sendMsg(viewID)
			}
			else if(MyPropertyLogic.getInstance().ui.visible)
			{
				sendMsg(MyPropertyLogic.getInstance().getEquipView())
			}
			else
			{
				//遍历伙伴装备节点  查找可疑装备的伙伴
				viewID	=	MyPropertyLogic.getInstance().findEqEmptyViewID(equitType);
				if(viewID==-1)
				{
					sendMsg(MyPropertyLogic.getInstance().getEquipView())
				}
				else
				{
					sendMsg(viewID);
				}
				
			
			}//MyPropertyLogic.getInstance().getEquipView()
			function sendMsg(viewPort:int):void
			{
				var index		:	int		=	GameDefine.EQPOS_HASH_MAP[ equitType ];
				if(itemObj.GetProperties("ItemType") ==GameDefine.ItemType_PET_EUIP)
				{
					index =0;
				}
				else if(itemObj.GetProperties("EquipType") == GameDefine.EquipType_Fashion)
				{
					viewPort = View.VIEWPORT_EQUIP;
				}
				SystemSender.getInstance().CustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_MOVEITEM,
					View.VIEWPORT_TOOL, int( itemObj.ObjKey ),
					viewPort, index );
			}
		}
		
		private function singleClick( evt : MouseEvent ):void
		{
			var cell:*	=	evt.target ;
			
			if(_gridData.indexOf(cell)	<	0)
			{
				var arr:Array	=	_gridData.filter(eachItem)
				cell	=	arr[0]//(evt.target as DisplayObject).parent as MovieClip;
			}
			
			if(cell.currentFrame	==	 DISABLE ||cell.currentFrame	==	 DISABLE_SELECTED)
			{
				SystemSender.getInstance().CustomMsg( CustomToServerFlag.CLIENT_CUSTOMMSG_EXPAND_TOOL_BOX, cell.index + 1 +(_currentPage-1)*_one_page_max);
				LogSendLogic.getInstance().btnClickNumSend(22805);
			}
			else
			{
				if( null != cell.dataobj &&cell.dataobj[_currentPage] )
				{
					MenuListManager.clickItem( PackLogic, cell.dataobj[_currentPage] );
				}
			}
			function eachItem(item:MovieClip,index:int,arr:Array):Boolean
			{
				return item.contains(cell);
			}
		}
		
		private function onClickItem(e:MouseEvent):void
		{
			_doubleClickManager.onClick( PackLogic, e );
		}
		
		private function onClickClose(e:Event):void
		{
			ui.showOrHide();
		}
		public function set rollCell(value:MovieClip):void
		{
			if(_roll_cell)
			{
				if(_roll_cell.currentFrame==ROLL)
					_roll_cell.gotoAndStop(NORMAL)
				else if(_roll_cell.currentFrame==DISABLE_SELECTED)
					_roll_cell.gotoAndStop(DISABLE);
			}
			
			_roll_cell=value;
			if(_roll_cell)
			{
				if(_roll_cell.currentFrame==NORMAL)
					_roll_cell.gotoAndStop(ROLL)
				else if(_roll_cell.currentFrame==DISABLE)
					_roll_cell.gotoAndStop(DISABLE_SELECTED);
			}
		}
		private function rollOver(e:Event):void
		{
			var cell:MovieClip	=	e.target as MovieClip;
			var arrr:Array=_gridData.filter(function(item:*,index:int,arr:Array):Boolean{
				return (item as DisplayObjectContainer).contains(e.target as DisplayObject);
			})
			cell=arrr[0]
			if(cell.dataobj)
			{
//				_tips.showByItem(_tips.getNormalItem(cell.dataobj));
				showTipsIndex(_gridData.indexOf(cell))
			}
//			if(cell.currentFrame!=DISABLE)
//			{
				rollCell=cell;
//			}
		}
		public function get tipIndex():int
		{
			return _tipIndex
		}
		private function showTipsIndex(index:int):void
		{
			if(!_roll_cell)return ;
			if(index >= 36) return;
			var cell:MovieClip=_gridData[index];
			_tipIndex=index;
			_tips.showMain(cell.dataobj[_currentPage]);
		}
		private function rollOut(e:Event):void
		{
			_tips.hide();
			rollCell=null
			
		}
		//卖装备
		public function sellEquip(tObj:ViewObject):void
		{
//			SellUI.getInstance().dispatchEvent(new Event("clicksale"));
			//只有一件的时候，提示参照装备
			if(tObj.CheckProperties("EquipType"))
			{
				if(tObj.GetProperties("EquipType") == "Fashion")  //时装
				{
					AlertUI.showAlert("",StaticIni.getSwfLangStr("UIString_1000694"),AlertUI.YES|AlertUI.NO, clickSellEquip,[tObj]);
					return;
				}
					
			}
			confirmsellEquip(tObj);
		}
		private function confirmsellEquip(tObj:ViewObject):void
		{
			var itemName:String = StaticIni.getSwfLangStr(tObj.GetPropertiesEx("NameID"));
			if(tObj.CheckProperties("Amount") && tObj.GetPropertiesEx("Amount") > 1)
			{
				SystemSender.getInstance().CustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_TRADE_WITHNPC,
					1,View.VIEWPORT_TOOL,tObj.GetProperties("ConfigID"),int(tObj.ObjKey),int(tObj.GetPropertiesEx("Amount")))
			}
			else
			{
				SystemSender.getInstance().CustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_TRADE_WITHNPC,
					1,View.VIEWPORT_TOOL,tObj.GetProperties("ConfigID"),int(tObj.ObjKey),1)
			}
		}
		private function clickSellEquip(clickName:uint,inputTxt:String,clickData:Array):void
		{
			if(clickName==AlertUI.YES)
			{
				confirmsellEquip(clickData[0] as ViewObject)
			}
			
		}
		
		/**
		 * 确定出售 
		 * @param clickName
		 * @param inputTxt
		 * @param clickData
		 * 
		 */		
		private function confirmSell(clickName:uint,inputTxt:String,clickData:Array):void
		{
			if(clickName==AlertUI.YES)
			{
				var saleAmount:int	=	1;
				if(uint(inputTxt)!=0)
				{
					saleAmount	=	uint(inputTxt);
				}
				SystemSender.getInstance().CustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_TRADE_WITHNPC,
					1,View.VIEWPORT_TOOL,clickData[0],clickData[1],saleAmount);
			}
		}
		/**
		 *按钮回调函数 
		 * @param e
		 * 
		 */		
		private function btnClickhandle(e:Event):void
		{
			var btn:NxButton	=	e.target as NxButton;
			if(!btn)return ;
			if(btn	==	ui.shopBtn)
			{
//				AlertUI.showAlert("提示","玩家消耗XX的货币");
				if(SellUI.getInstance().created)
				{
					SellUI.getInstance().showOrHide();
				}
				else
				{
					SystemSender.getInstance().CustomMsg(
					CustomToServerFlag.CLIENT_CUSTOMMSG_OPEN_POCKET_STORE);
				}
				
			}
			if(btn==ui.clearUpBtn)
			{
				//整理
				SystemSender.getInstance().CustomMsg(
					CustomToServerFlag.CLIENT_CUSTOMMSG_ARANGEITEM,
					View.VIEWPORT_TOOL,0,0);
				_model.dispatchEvent(new SoundEvent(SoundEvent.PACKET_SORT));
			}
			if(btn	==	ui.storageBtn)
			{
//				AlertUI.showAlert("提示","弹窗提示玩家消耗XX的货币");
				DepotUI.getInstance().showOrHide();	
//				DepotUI.getInstance().windowBG.x=ui.windowBG.x+ui.width;
//				DepotUI.getInstance().windowBG.y=ui.windowBG.y;
			}
			
		}
		/**
		 *简单刷新 
		 * 
		 */		
		private function refresh():void
		{
			ui.group.reSet()
			for (var i:int = 0; i < ui.group.col*ui.group.row; i++) 
			{
				ui.group.getItemByIndex(i).addChild(_gridData[i]);
			}
		}
		public function addChildren(pa:DisplayObjectContainer,...args):void
		{
			for each (var i:DisplayObject in args) 
			{
				pa.addChild(i)
			}
		}
		public function BeforeShow():void
		{
			if(!SceneManager._itemIconLoad)
			{
				_model.addEventListener(LogicEvent.ITEMICONLOADED,loaded);
				function loaded():void
				{
					removeAllListener();
					PackLogic.getInstance().bindFlag = -1;
					PackLogic.getInstance().bindView = -1;
					BeforeShow();
					_model.removeEventListener(LogicEvent.ITEMICONLOADED,loaded)
				}
			}
			
			addAllListener();
			if( bindFlag == -1 )
			{
				bindFlag		=	_blind.BindView(_model.scene,View.VIEWPORT_TOOL,OnAddPack,OnRemovePack);

			}
			if(bindView	==	-1)
			{
				bindView	 = _blind.BindProp(_model.scene.GetView(View.VIEWPORT_TOOL),"BaseCap",this,"unlock")
			}
		}
		public function afterhide():void
		{
			removeAllListener();
			if( bindFlag != -1 )
			{
				bindFlag		=	_blind.UnbindView(View.VIEWPORT_TOOL,bindFlag);
			}
			if(bindView != -1)
			{
				bindView	 = _blind.UnbindProp(_model.scene.GetView(View.VIEWPORT_TOOL),"ExpandToolBoxCap",bindView)
			}
			clearAll();
		}
		private function clearAll():void
		{
			for each (var i:MovieClip in _gridData) 
			{
				clearProperty(_gridData.indexOf(i));
			}
			
		}
		/**
		 *添加遮罩 
		 * 
		 */		
		private function addVeil(mc:MovieClip):void
		{
			var ViewObj:ViewObject=mc.dataobj[_currentPage];
			var color:String =ViewObj.GetProperties("Color");
			var panle:MovieClip = McPool.borrowRes(_veilArr[int(color)-1]) as MovieClip; 
			if(panle==null)
				return;
			mc.addChild(panle);
			panle.x=3.5;
			panle.y=4
			mc["Veil"]=panle;
//			mc["data"]=ViewObj;
			if(_propData.indexOf(mc)==-1)
			{
				_propData.push(mc);
			}
				
		}
		/**
		 *删除遮罩 
		 * @param mc
		 * 
		 */		
		private function removeVeil(mc:MovieClip):void
		{
			if(mc["Veil"])
			{
				McPool.returnRes( mc["Veil"].url, mc["Veil"].parent.removeChild(mc["Veil"]));
//				mc["data"]=null;
				mc["Veil"]=null;
			}
		}
			
		/**
		 * 绑定回调
		 *设置取消上锁的数量 
		 * @param value
		 * 
		 */		
		public function set unlock(value:int):void
		{
			if(getIndexIsCurrentPage(value))
			{
				_unlock	=	value%_one_page_max//int(_model.scene.GetView(View.VIEWPORT_TOOL).GetPropertiesEx("BaseCap"));
			}
			else if(value>(_currentPage-1)*_one_page_max)
			{
				_unlock	=	_one_page_max
			}
			else 
			{
				_unlock=0
			}
			if(_unlock>_lockIndex)
			{
				for (var i:int = _lockIndex; i < _unlock; i++) 
				{
					var cellt:MovieClip	=	_gridData[i]
					cellt.gotoAndStop(NORMAL);
				}
			}
			else
			{
				for (i = _unlock; i < _lockIndex; i++) 
				{
					cellt	=	_gridData[i]
					cellt.gotoAndStop(DISABLE);
				}
			}
			_lockIndex			=	_unlock;
			_unlock	=	value
			ui.countTxT.htmlStr	=	StaticIni.getSwfLangStrVar("UIString_1000001",[_unlock,_ui.page.dataProvider.length*_one_page_max]);
		}
		
		private function OnAddPack(PropertiesName:String,PropertiesValue:ViewObject,data:*):void
		{
			var index:int		=	int(PropertiesValue.ObjKey)-1
			var mc:MovieClip	=	_gridData[index%_one_page_max];
			if(!mc.dataobj)
			{
				mc.dataobj	=	{};
			}
			mc.blindflag		=	BindManage.getInstance().UnbindProp(mc.dataobj[mc.currentPage],"Amount",mc.blindflag);
			mc.dataobj[int(index/_one_page_max)+1]			=	PropertiesValue
			refreshIndex(index);
			if(/*index==tipIndex*/_tips.isMainShow)
			{
				showTipsIndex(index)
			}
		}
		/**
		 *检查index位置是不是在当前页 
		 * @param index
		 * @return 
		 * 
		 */		
		private function getIndexIsCurrentPage(index:int):Boolean
		{
			return int(index/_one_page_max)+1==_currentPage;
		}
		private function refreshIndex(index:int):void
		{
			if(getIndexIsCurrentPage(index))
			{
				refreshProperty(index%_one_page_max);
			}
		}
		private function refreshProperty(index:int):void
		{
			var mc:MovieClip			=	_gridData[index];
			var value:ObjectData;
			if(	mc.dataobj)
			{
				value	=	mc.dataobj[_currentPage]
			}
			if(value)
			{
				removeVeil(mc);
				mc.bg.source			=	ResourcesPath.getPropsURL(value.GetProperties("Photo"));
				if(value.CheckProperties("Amount"))
				{
//					trace("PackLogic.refreshProperty(index)",value.GetPropertiesEx("Amount"),StaticIni.getSwfLangStr(value.GetPropertiesEx("ConfigID")));
//					mc.blindflag		=		BindManage.getInstance().BindProp(value,"Amount",mc.lable,"htmlStrByBorder");
					mc.currentPage		=_currentPage;
					mc.blindflag		=BindManage.getInstance().BindPropInViewObj(value.parent as View,value.ObjKey,"Amount",BindFunc,null,[mc.lable,"htmlStrByBorder"]);
					mc.lable.visible	=	true;
				}
				else
				{
					mc.lable.htmlStr	=	"";
					mc.lable.visible		=	false
				}
				addVeil(mc);
			}
			else
			{
				if(mc.blindflag||mc.blindflag==0)
				{
					mc.blindflag		=		BindManage.getInstance().UnbindProp(value,"Amount",mc.blindflag);
				}
				mc.bg.clear();
				mc.bg.source			=	null;
				mc.lable.htmlStr	=	"";
				mc.lable.visible		=	false;
				removeVeil(mc);
			}
		}
		public function BindFunc(PropertiesName:String,PropertiesValue:*,pList:Array):void
		{
			var		Obj:NxLabel	=	pList[0];
			var		value:*		=	pList[1];
			var perWidth:int	=	5;
			Obj.x=32-perWidth*(String(PropertiesValue).length-1)
			Obj[value]=PropertiesValue;	
		}
		/**
		 * 
		 * @param index
		 * 
		 */		
		private function clearProperty(index:int):void
		{
			var mc:MovieClip=_gridData[index];
			mc.dataobj			=	null;
			refreshProperty(index);
		}
		private function OnRemovePack(PropertiesName:String,PropertiesValue:ViewObject,data:*):void
		{
			var itemPos:int		=	 uint(PropertiesValue.ObjKey)-1;
			var mc:MovieClip	=	_gridData[(itemPos%_one_page_max)];
			mc.blindflag		=	BindManage.getInstance().UnbindProp(mc.dataobj[mc.currentPage],"Amount",mc.blindflag);
			mc.dataobj[int(itemPos/_one_page_max)+1]			=	null;
			refreshIndex(itemPos);
		}
		public function get isPackFull():Boolean
		{
			return MainLogic.getInstance().checkViewFull(View.VIEWPORT_TOOL,"BaseCap");
		}
		public function get ui():PackUI
		{
			if(_ui==null)
			{
				_ui	=	new PackUI();
			}
			return _ui
		}
	}
}
